package com.leenmvc.core.security.service.core;

import com.leenmvc.core.annotation.TransactionMulti;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.dao.core.SysRolePermissionDao;
import com.leenmvc.core.security.entity.core.SysRolePermission;
import com.leenmvc.core.utils.TipUtil;
import com.leenmvc.core.utils.unique.SnowFlake;
import com.leenmvc.core.utils.validator.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 权限操作服务层代码
 */
@Service
public class SysRolePermissionService extends BaseService<SysRolePermission> {

    @Autowired
    private SysRolePermissionDao sysRolePermissionDao;

    @TransactionMulti
    @Override
    public <T> boolean insert(T t) {
        SysRolePermission srp = (SysRolePermission) t;
        ValidatorUtils.notNull(TipUtil.getTip("NOTNULL_FAIL"), srp.getPermissionList());
        Long[] permissionList = srp.getPermissionList();
        if (permissionList!=null) {
            int length = permissionList.length;
            for (int i = 0; i < length; i++) {
                srp.setId(SnowFlake.generateId());
                srp.setPermissionId(permissionList[i]);
                if (!sysRolePermissionDao.insert(srp)){
                    return false;
                }
            }
        } else if (srp.getPermissionId()!=null) {
            if (!sysRolePermissionDao.insert(srp)){
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    @TransactionMulti
    @Override
    public <T> boolean update(T t) {
        SysRolePermission srp = (SysRolePermission) t;
        if (srp.getPermissionList()!=null){
            if (srp.getPermissionList().length>1) {
                throw new BusinessException("不能够同时修改两项，请检查！");
            }
            srp.setPermissionId(srp.getPermissionList()[0]);
            if (!sysRolePermissionDao.update(srp)) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    @Override
    public <T> T get(Object id) {
        SysRolePermission sysRolePermission = sysRolePermissionDao.get(id);
        if(null == sysRolePermission){
            return null;
        }
        Long permissionId = sysRolePermission.getPermissionId();
        Long[] permissionList = sysRolePermission.getPermissionList();
        permissionList = new Long[]{permissionId};
        sysRolePermission.setPermissionList(permissionList);
        sysRolePermission.setPermissionId(null);
        return (T) sysRolePermission;
    }
}
